// 贪吃蛇游戏类
class SnakeGame {
    constructor() {
        this.canvas = document.getElementById('snake-canvas');
        this.ctx = this.canvas.getContext('2d');
        
        this.GRID_SIZE = 20;
        this.BOARD_WIDTH = this.canvas.width / this.GRID_SIZE;
        this.BOARD_HEIGHT = this.canvas.height / this.GRID_SIZE;
        
        this.snake = [];
        this.food = {};
        this.direction = { x: 1, y: 0 };
        this.nextDirection = { x: 1, y: 0 };
        this.score = 0;
        this.isGameRunning = false;
        this.gameLoop = null;
        
        this.bindEvents();
        this.loadAndDisplayGameData();
    }

    // 初始化游戏
    initGame() {
        this.snake = [
            { x: Math.floor(this.BOARD_WIDTH / 2), y: Math.floor(this.BOARD_HEIGHT / 2) }
        ];
        this.direction = { x: 1, y: 0 };
        this.nextDirection = { x: 1, y: 0 };
        this.score = 0;
        this.generateFood();
        this.updateScore();
    }

    // 开始游戏
    async startGame() {
        this.initGame();
        this.isGameRunning = true;
        await this.updateGameStats();
        this.gameLoop = setInterval(() => this.update(), 150);
        this.draw();
    }

    // 停止游戏
    stopGame() {
        this.isGameRunning = false;
        if (this.gameLoop) {
            clearInterval(this.gameLoop);
            this.gameLoop = null;
        }
    }

    // 游戏更新
    update() {
        if (!this.isGameRunning) return;

        // 更新方向
        this.direction = { ...this.nextDirection };

        // 移动蛇头
        const head = { ...this.snake[0] };
        head.x += this.direction.x;
        head.y += this.direction.y;

        // 检查碰撞
        if (this.checkCollision(head)) {
            this.gameOver();
            return;
        }

        this.snake.unshift(head);

        // 检查是否吃到食物
        if (head.x === this.food.x && head.y === this.food.y) {
            this.score += 10;
            this.updateScore();
            this.generateFood();
        } else {
            this.snake.pop();
        }

        this.draw();
    }

    // 检查碰撞
    checkCollision(head) {
        // 撞墙
        if (head.x < 0 || head.x >= this.BOARD_WIDTH || 
            head.y < 0 || head.y >= this.BOARD_HEIGHT) {
            return true;
        }

        // 撞自己
        for (const segment of this.snake) {
            if (head.x === segment.x && head.y === segment.y) {
                return true;
            }
        }

        return false;
    }

    // 生成食物
    generateFood() {
        do {
            this.food = {
                x: Math.floor(Math.random() * this.BOARD_WIDTH),
                y: Math.floor(Math.random() * this.BOARD_HEIGHT)
            };
        } while (this.snake.some(segment => 
            segment.x === this.food.x && segment.y === this.food.y
        ));
    }

    // 绘制游戏
    draw() {
        // 清空画布
        this.ctx.fillStyle = '#2C3E50';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

        // 绘制网格
        this.ctx.strokeStyle = '#34495E';
        this.ctx.lineWidth = 1;
        for (let x = 0; x <= this.canvas.width; x += this.GRID_SIZE) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, 0);
            this.ctx.lineTo(x, this.canvas.height);
            this.ctx.stroke();
        }
        for (let y = 0; y <= this.canvas.height; y += this.GRID_SIZE) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, y);
            this.ctx.lineTo(this.canvas.width, y);
            this.ctx.stroke();
        }

        // 绘制蛇
        this.snake.forEach((segment, index) => {
            this.ctx.fillStyle = index === 0 ? '#27AE60' : '#2ECC71';
            this.ctx.fillRect(
                segment.x * this.GRID_SIZE + 1,
                segment.y * this.GRID_SIZE + 1,
                this.GRID_SIZE - 2,
                this.GRID_SIZE - 2
            );
        });

        // 绘制食物
        this.ctx.fillStyle = '#E74C3C';
        this.ctx.beginPath();
        this.ctx.arc(
            this.food.x * this.GRID_SIZE + this.GRID_SIZE / 2,
            this.food.y * this.GRID_SIZE + this.GRID_SIZE / 2,
            this.GRID_SIZE / 2 - 2,
            0,
            Math.PI * 2
        );
        this.ctx.fill();
    }

    // 游戏结束
    async gameOver() {
        this.stopGame();
        await this.saveGameData();
        const data = await this.loadGameData();
        alert(`游戏结束！\n得分: ${this.score}\n长度: ${this.snake.length}\n最高分: ${data.highScore}`);
    }

    // 更新分数显示
    updateScore() {
        document.getElementById('snake-score').textContent = this.score;
        document.getElementById('snake-length').textContent = this.snake.length;
    }

    // 绑定事件
    bindEvents() {
        document.addEventListener('keydown', (e) => {
            if (!this.isGameRunning) return;

            switch (e.key) {
                case 'ArrowUp':
                    if (this.direction.y === 0) {
                        this.nextDirection = { x: 0, y: -1 };
                    }
                    break;
                case 'ArrowDown':
                    if (this.direction.y === 0) {
                        this.nextDirection = { x: 0, y: 1 };
                    }
                    break;
                case 'ArrowLeft':
                    if (this.direction.x === 0) {
                        this.nextDirection = { x: -1, y: 0 };
                    }
                    break;
                case 'ArrowRight':
                    if (this.direction.x === 0) {
                        this.nextDirection = { x: 1, y: 0 };
                    }
                    break;
            }
        });
    }

    // 保存游戏数据
    async saveGameData() {
        const currentData = await this.loadGameData();
        const gameData = {
            highScore: Math.max(this.score, currentData.highScore || 0),
            lastScore: this.score,
            gamesPlayed: (currentData.gamesPlayed || 0) + 1
        };
        await authManager.saveGameData('snake', gameData);
    }

    // 加载游戏数据
    async loadGameData() {
        return await authManager.loadGameData('snake') || { highScore: 0 };
    }

    // 更新游戏统计显示
    async updateGameStats() {
        const data = await this.loadGameData();
        document.getElementById('snake-high-score').textContent = data.highScore || 0;
    }

    // 加载并显示游戏数据
    async loadAndDisplayGameData() {
        await this.updateGameStats();
    }
}

// 创建游戏实例
let snakeGame;